import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    PageContainer,
    ProDescriptions, ProFormCheckbox,
    ProTable,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Tag, Badge, Space, Statistic} from 'antd';
import React, {useRef, useState} from 'react';
import type {SkuListItem} from './data';
import {skuList, skuAdd, skuEdit, removeSku} from './service';
import {Link} from "react-router-dom";

const {confirm} = Modal;
/**
 * 添加节点
 *
 * @param fields
 */

/**
 * 更新节点
 *
 * @param fields
 */

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
} & Partial<SkuListItem>;

/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: SkuListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await removeSku({
            skuIds: selectedRows.map((row) => row.skuId),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};


const SkuList: React.FC = () => {
    /** 新建窗口的弹窗 */
    /** 分布更新窗口的弹窗 */
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<SkuListItem>();
    const [selectedRowsState, setSelectedRows] = useState<SkuListItem[]>([]);
    /** 国际化配置 */
    const columns: ProColumns<SkuListItem>[] = [
        {
            title: '规格ID',
            dataIndex: 'skuId',
            search: false,
            ellipsis: true, // 关闭自动换行
            hidden: true,
        },
        {
            title: '规格名称',
            dataIndex: 'skuName',
            ellipsis: true, // 关闭自动换行
            search: true,
            render: (dom, entity) => {
                return (
                    <a
                        onClick={() => {
                            setCurrentRow(entity);
                            setShowDetail(true);
                        }}
                    >
                        {dom}
                    </a>
                );
            },
        },
        {
            title: '品牌',
            dataIndex: 'brand',
            ellipsis: true, // 关闭自动换行
            search: false,
        },
        {
            title: '算力',
            dataIndex: 'hashrate',
            ellipsis: true, // 关闭自动换行
            search: false,
            renderText: (val: number) => `${val}P`,
        },
        {
            title: 'CPU',
            dataIndex: 'cpu',
            ellipsis: true, // 关闭自动换行
            search: false,
        },
        {
            title: 'GPU信息',
            // dataIndex: 'admin',
            dataIndex: 'gpu',
            ellipsis: true, // 关闭自动换行
            search: false,
        },
        {
            title: '连接方式',
            dataIndex: 'gpuConn',
            ellipsis: true, // 关闭自动换行
            search: false,
        },
        {
            title: '存储信息',
            dataIndex: 'storageType',
            ellipsis: true, // 关闭自动换行
            search: false,
        },
        {
            title: '组网方式',
            dataIndex: 'networking',
            ellipsis: true, // 关闭自动换行
            search: false,
        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            ellipsis: true, // 关闭自动换行
            render: (_, record) => {
                var link = `/power/sku-edit/` + record.skuId
                return <div style={{width: 150, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>
                    <Link to={link}>
                        编辑
                    </Link>
                </div>
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<SkuListItem, API.ListPagination>
                headerTitle="规格列表"
                actionRef={actionRef}
                rowKey="skuId"
                search={{
                    labelWidth: 70,
                }}
                scroll={{x: true}}
                toolBarRender={() => [
                    <Link to={"/power/sku-add"}>
                        <Button
                            type="primary"
                            key="primary"
                        >
                            <PlusOutlined/> 新建
                        </Button>
                    </Link>,
                ]}
                request={skuList}
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
                expandable={{
                    expandedRowRender: (record) => {
                        let result = [];
                        for (let i = 0; i < record.ext.length; i++) {
                            if (record.ext[i].comment) {
                                result.push(
                                    <div key={i} style={{marginTop: 10, marginLeft: 80}}>
                                        <b>{record.ext[i].comment}: </b>
                                        {record.ext[i].value}
                                        {i < record.ext.length - 1 && <br/>}
                                    </div>
                                );
                            } else {
                                result.push(
                                    <div key={i} style={{marginTop: 10, marginLeft: 80}}>
                                        {record.ext[i].value}
                                        {i < record.ext.length - 1 && <br/>}
                                    </div>
                                );
                            }
                        }
                        return <div>{result}</div>;
                    },
                    rowExpandable: (record) => record.ext?.length > 0,
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '删除规格',
                                // icon: <ExclamationCircleFilled />,
                                content: '删除规格前，请确认规格关联主机等资源已清除，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}
        </PageContainer>
    );
};

export default SkuList;
